package jp.co.cos.ittrick.channel.controller.client;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import jp.co.cos.ittrick.channel.meta.ChapterModelMeta;
import jp.co.cos.ittrick.channel.model.CategoryModel;
import jp.co.cos.ittrick.channel.model.ChapterModel;
import jp.co.cos.ittrick.channel.service.CategoryService;
import jp.co.cos.ittrick.channel.service.ChapterService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.oauth.OAuthService;
import com.google.appengine.api.oauth.OAuthServiceFactory;
import com.google.appengine.api.users.User;

public class InsertChapterController extends Controller {

    private ChapterService chapterService;
    private CategoryService categoryService;

    public InsertChapterController() {
        chapterService = new ChapterService();
        categoryService = new CategoryService();
    }

    @Override
    public Navigation run() throws Exception {

        // リクエストパラメータ
        String category = asString("category");
        String name = asString("name");
        Integer index = this.asInteger("index");

//        Logger logger = Logger.getLogger(this.getClass().getName());
//        OAuthService oauthService = OAuthServiceFactory.getOAuthService();
////        User user = oauthService.getCurrentUser();
//        logger.info("OAuth User:" + oauthService.isUserAdmin());

        List<String> keyWordList = new ArrayList<String>();

        // 親の取得
        CategoryModel categoryModel = categoryService.getCategoryByKey(Integer.valueOf(category));

        // Modelの設定
        ChapterModel model = new ChapterModel();
        model.setName(name);
        model.setIndex(index);
        model.setKeyWordList(keyWordList);
        model.getCategoryModelRef().setModel(categoryModel);

        // Insert
        Key key = chapterService.insert(model);

        model = chapterService.getChapterByKey((int)key.getId());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        response.getWriter().println(ChapterModelMeta.get().modelToJson(model));
        response.flushBuffer();

        return null;
    }
}
